/* webtrends 统计
@type
@label
@event
@className
*/
import React,{PropTypes} from 'react'
import RComponent from '../../components'
import Cookie from 'react-cookie'
import * as Utils from '../../utils'
import Info from '../../utils/info'

class Sdc extends RComponent {
    constructor(props,context){
        super(props,context)
    }

    componentDidMount(){
        let {type} = this.props;
        if(type == 'page'){
            this.sendSdc();
        }
    }

    initSdc(){
        this.sdc = {};

        let params = Utils.parseParameter();
        // 平台（android/ios/pc等
        let platform = 'unknow';
        let p = info.platform();
        // 客户端（App/微信/H5等）
        let client = info.client;
        if(p.isIos){
            platform = 'ios'
        }
        if(p.isAndroid){
            platform = 'android'
        }
        // if(p.isAneApp){
        //     platform = 'pazqapp'
        // }
        if(!p.isAneApp){
            platform = 'web'
        }


        //aid,sid,ouid,获客渠道编码
        let aid = params.aid || "";
        let sid = params.sid || "";
        let ouid = params.ouid || "";
        let channelCode = Utils._getChannelCode(aid,sid,ouid);
        // 如果没有任何值时，取cookies上一个的值
        if(channelCode.length<=4){
            channelCode =  Cookie.load('sdcAainSourceChannel');
        }
        Cookie.save('sdcAainSourceChannel',channelCode,{expires:5*24*60*60*1000,path:'/'})

        // 内媒（用于区分微信的服务号和订订阅号，PC的通达信）
        let innerMedia = params.inner_media || Cookie.load('sdcSubagent');
        // 媒体来源
        let mc_id = params['WT.mc_id'] || '';
        // 内部入口
        let inner_entry = params['inner_entry'] || '';
        // 推荐人
        let t = params['t'];
        // 内媒体需要自动延续
        Cookie.save('sdcSubagent',innerMedia,{expires:5*24*60*60*1000,path:'/'});

        // 如果 媒体来源 mc_id存在，媒体来源3天内有效，不会延续
        if(mc_id){
            Cookie.save('sdcSource',mc_id,{expires:3*24*60*60*1000,path:'/'});
        }
        // 如果 内部入口 inner_entry存在，内部来源3天内有效，不会延续
        if(inner_entry){
            this.sdc["sdcInnerEntry"] = inner_entry;
        }
        // 如果 推荐人 t存在，推荐人3天内有效，不会延续
        if(t){
            Cookie.save('sdcReferee',t,{expires:3*24*60*60*1000,path:'/'});
        }

        Cookie.save('sdcPlatform',platform,{path:'/'});
        Cookie.save('sdcAgent',client,{path:'/'});

        this.sdc=Object.assign({},this.sdc,{
            sdcReferee:t || Cookie.load('sdcReferee'),
            sdcSource:mc_id || Cookie.load('sdcSource'),
            sdcVisitorId:"",                                // 访客ID
            sdcPlatform:platform,
            sdcAgent:client,
            sdcInnerEntry:inner_entry || Cookie.load('sdcInnerEntry'),
            sdcAainSourceChannel:channelCode,
            sdcSubagent:innerMedia
        })

        if(info.isAneApp && (!channelCode || (channelCode && channelCode.length<=4))){
            // 在app中，取默认的aid\sid\ouid
            Native.getConditions(function(data){
                if(!data)return;
                channelCode = Utils._getChannelCode(data.aid,data.sid,data.ouid);
                this.sdc["sdcAainSourceChannel"] = channelCode;
            })
        }
    }

    sendSdc(){
        let {dispatch, type, label, event} = this.props;
        // post
        console.log('type:'+type+' label:'+label+' event:'+event)

        let data = this.sdc
        //任意门talkingdata埋点
        if (navigator.userAgent.match(/anydoor/ig)) {
            // //任意门灵活宝插件id
            // if (!data.pluginId) {
            //     data.pluginId = 'PA01100000000_02_LHBLC';
            // }
            // if (window.RYMJSBRIDGE) {
            //     window.RYMJSBRIDGE.saveTalkingData(data, success, fail);
            // } else {
            //     this._rymSendTalkingData(data, success, fail);
            // }
        } else if (window.pa_sdcajax) {// 用webtrend来代替埋点
            setTimeout(function() {
                pa_sdcajax('WT.td_data', JSON.stringify(data), true);
            }, 10)
        }
    }

    _rymSendTalkingData(data,sucess,fail){
        var slice = Array.prototype.slice;
        var toString = Object.prototype.toString;
        var callindex = 0;

        function _rymAdapter(name) {
            let p = info.platform();
            // 获取传递给Native方法的参数
            var args = slice.call(arguments, 1);
            var successCallback = '', errorCallback = '', item = null, returnArg;
            var methodName = name[name.length - 1];

            if (p.isAndroid && p.isAnydoor) {
                if (window.HostApp) {
                    var _str = "", newArguments = [];
                    for (var i = 0; i < args.length; i++) {
                        if (typeof args[i] === 'function') {
                            var callbackName = methodName + 'Callback' + callindex;
                            window[callbackName] = args[i];
                            newArguments.push(callbackName);
                            callindex++;
                        } else if (typeof args[i] === 'object') {
                            newArguments.push(JSON.stringify(args[i]));
                        } else {
                            newArguments.push(args[i]);
                        }
                    }
                    try {
                        HostApp[methodName].apply(window.HostApp, newArguments);
                    } catch (e) {
                    }
                } else {
                    var params = slice.call(arguments, 0);
                    setTimeout(function () {
                        app["call"].apply(app, params);
                    }, 1000);
                }
            } else if (p.isIos && p.isAnydoor) {
                var newArguments = "", tempArgument = [];
                for (var i = 0; i < args.length; i++) {
                    if (typeof args[i] === 'function') {
                        var callbackName = methodName + 'Callback' + callindex;
                        window[callbackName] = args[i];
                        tempArgument.push(callbackName);
                        callindex++;
                    } else {
                        tempArgument.push(args[i]);
                    }
                }
                callindex++;
                var iframe = document.createElement("iframe");
                var _src = 'callnative://' + methodName + '/' + encodeURIComponent(JSON.stringify(tempArgument)) + '/' + callindex;
                iframe.src = _src;
                iframe.style.display = "none";
                document.body.appendChild(iframe);
                iframe.parentNode.removeChild(iframe);
                iframe = null;
            }
        }
        /**
         * 任意门发送talkingData
         */
        // return function (data, success, fail) {
            _rymAdapter(["saveTalkingData"],
                function(e) {
                    var data;
                    try{
                        data = JSON.parse(e);
                    } catch(error){
                        data = e;
                    }
                    success && success(data);
                },
                function(e) {
                    var data;
                    try{
                        data = JSON.parse(e);
                    } catch(error){
                        data = e;
                    }
                    fail && fail(data);
                }, {
                    label: data.label,
                    event: data.event,
                    pluginId: data.pluginId,
                    map: data.map
                }
            )
        // }
    }

    handleClick(){
        let {type} = this.props;
        if(type == 'page'){
            return;
        }
        this.sendSdc();
    }

    render(){
        return (
            <div onClick={this.handleClick.bind(this)} className={this.props.className}>
                { this.props.children }
            </div>
        )
    }
}
Sdc.propTypes = {
    type:PropTypes.string, // page|button|input|select|password
    label:PropTypes.string,
    event:PropTypes.string,
    map:PropTypes.string,
    innerEntry:PropTypes.string,
    innerMedia:PropTypes.string
}

export default Sdc;
